package com.work.demo.handler;

import com.work.demo.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

/**
 * @ProjectName: demo
 * @Package: com.example.demo.handler
 * @ClassName: AllExceptionHandler
 * @Author: Deng YuBin
 * @Description: 全局异常捕捉处理
 * @Date: 2022/2/19 13:38
 * @Version: 1.0
 */
@ControllerAdvice
@Slf4j
public class AllExceptionHandler {

    @ExceptionHandler(Exception.class)
    public R<?> handleBusinessException(Exception e){
//        log.error("异常{}",getStackTraceByPn(e));
        log.error("异常{}",e);
        return R.failed(e.getMessage());
    }

    //过滤堆栈错误信息的方法
    private static String getStackTraceByPn(Throwable e){
        StringBuilder s = new StringBuilder("\n").append(e);
        for (StackTraceElement traceElement : e.getStackTrace()) {
            if (!traceElement.getClassName().startsWith("mayfly.")){
                continue;
            }
            s.append("\n\tat ").append(traceElement);
        }

        return s.toString();
    }
}
